<?php


namespace app\admin\controller;


use app\admin\controller\BaseController;
use app\common\exception\MessageException;
use app\common\model\mysql\ArticleCategory as ArticleCategoryModel;
use app\common\validate\CategoryValidate;
use app\common\validate\IDMustBePositiveInt;

class ArticleCategory extends BaseController
{
    public function list()
    {
        try {
            // 分页查询
            $params = $this->request->param();
            $result = ArticleCategoryModel::list($params);

            return $this->renderSuccess($result);
        } catch (\Exception $e) {
            throw new MessageException(['msg' => $e->getMessage()]);
        }
    }

    public function create()
    {
        if (!$this->request->isPost()) {
            throw new MessageException(['msg' => '请求方法不合法']);
        }
        (new CategoryValidate())->goCheck();
        $data = $this->request->param();
        try {
            $Model = new ArticleCategoryModel();
            $findData = $Model->checkName($data['name']);

            if ($findData) {
                return $this->renderFail('分类名称已存在');
            }

            $result = $Model->create($data);
            if ($result) {
                return $this->renderSuccess([], '添加成功');
            }

        } catch (\Exception $e) {
            throw new MessageException(['msg' => $e->getMessage()]);
        }
    }

    public function update()
    {
        if (!$this->request->isPost()) {
            throw new MessageException(['msg' => '请求方法不合法']);
        }
        (new CategoryValidate())->goCheck();
        $data = $this->request->param();

        try {
            $Model = new ArticleCategoryModel();
            $findData = $Model->checkName($data['name'], $data['id']);

            if ($findData) {
                return $this->renderFail('分类名称已存在');
            }

            $result = $Model->update($data);
            if ($result) {
                return $this->renderSuccess([], '添加成功');
            }

        } catch (\Exception $e) {
            throw new MessageException(['msg' => $e->getMessage()]);
        }
    }

    public function delete()
    {
        (new IDMustBePositiveInt())->goCheck();
        $params = $this->request->param();

        try {
            $Model = new ArticleCategoryModel();
            $findData = $Model->find($params['id']);

            if (!$findData) {
                return $this->renderFail('分类不存在');
            }

            $result = $Model->update(['id' => $params['id'], 'status' => config('status.mysql.delete')]);
            if ($result) {
                return $this->renderSuccess([], '删除成功');
            }

        } catch (\Exception $e) {
            throw new MessageException(['msg' => $e->getMessage()]);
        }
    }
}